//
//  PersonViewController.swift
//  cysLibrarySys
//
//  Created by 曹亚索 on 2021/6/25.
//

import UIKit
import ViewAnimator
import ZKProgressHUD

var Module = PersonView().module

@available(iOS 13.0, *)
class PersonViewController: UIViewController {
    
    private var currentIndex: IndexPath!
    private let Login = LoginViewController()
    private let personDetailViewController = PersonDetailView()
    private let reuseIdentifier = "PersonCell"
    private let pickAvatarViewWidth = UIScreen.main.bounds.width / 1.5
    private let avatarBottomLabelAlpha: CGFloat = 0.8
    private var avatarBottomLabel: UILabel!
    @IBOutlet weak var userAvatar: UIImageView!
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var moduleTableView: UITableView!
    private var modules : [String] = ["我的收藏","我的借阅","我的分享","设置","登录"]
    private var setions : [String] = ["修改资料","修改密码","注销账号","取消"]
    
    private lazy var PickAvatarView : UICollectionView = {
        let viewFrame = CGRect(origin: .zero, size: CGSize(width: pickAvatarViewWidth, height: pickAvatarViewWidth))
        let layout = EditAvatarViewLayout()
        let collectionView = EditAvatarView(frame: viewFrame, collectionViewLayout: layout)
        collectionView.center = self.view.center
        collectionView.pickAvatar = self
        layout.itemSize = CGSize(width: collectionView.frame.width, height: 87)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        return collectionView
    }()
    
    private lazy var clearView : UIView = {
        let view = UIView()
        view.backgroundColor = .gray
        view.alpha = 0.2
        view.frame = self.view.frame
        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissPickAvatarView(tap:))))
        return view
    }()
    
    @objc private func dismissPickAvatarView(tap:UIGestureRecognizer){
        switch tap.state {
        case .ended:
            PickAvatarView.removeFromSuperview()
            clearView.removeFromSuperview()
        default:
            break
        }
    }
    //MARK:Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        commonInit()
    }
    
    private func commonInit(){
        setUpModuleTableView()
        setUpUserAvatar()
        setUpUserNameLabel()
    }
    
    private func setUpUserNameLabel(){
        if let user = userSelf{
            userName.text = user.name
        }
    }

    private func setUpModuleTableView(){
        moduleTableView.dataSource = self
        moduleTableView.delegate = self
        moduleTableView.tableFooterView = UIView.init(frame: CGRect.zero)
        let nib = UINib(nibName: reuseIdentifier, bundle: nil)
        self.moduleTableView.register(nib, forCellReuseIdentifier: String(describing: PersonCell.self))
    }
    
    private func setUpUserAvatar(){
        if let imageName = userSelf?.avatar{
            userAvatar.image = UIImage(named: imageName)
        }
        userAvatar.layer.cornerRadius = userAvatar.frame.width/2
        userAvatar.layer.borderWidth = 1
        userAvatar.layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        userAvatar.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(editAvatar(tap:))))
        setUpBottomLabel()
    }
    
    private func setUpBottomLabel(){
        avatarBottomLabel = UILabel()
        //configuration
        avatarBottomLabel.font = UIFont(name: "System", size: 12)
        avatarBottomLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        avatarBottomLabel.alpha = avatarBottomLabelAlpha
        if userSelf != nil{
            if userSelf?.avatar != nil{
                avatarBottomLabel.alpha = 0
            }else{
                avatarBottomLabel.text = "点击编辑"
            }
        }else{
            avatarBottomLabel.text = "点击登录"
        }
        avatarBottomLabel.textAlignment = .center
        avatarBottomLabel.backgroundColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
        //constraint
        avatarBottomLabel.frame = CGRect(x: 0, y: userAvatar.frame.maxY - userName.frame.height, width: userName.frame.width, height: userName.frame.height)
        avatarBottomLabel.center.x = userAvatar.center.x
        userAvatar.addSubview(avatarBottomLabel)
    }
    
    @objc private func editAvatar(tap:UIGestureRecognizer){
        switch tap.state {
        case .ended:
            if userSelf != nil{
                self.view.addSubview(clearView)
                self.view.addSubview(PickAvatarView)
                let actionFrom = AnimationType.from(direction: .bottom, offset: 100)
                PickAvatarView.animate(animations: [actionFrom])
            }else{
                let vc = LoginViewController()
                vc.turnSignUpDelegate = self
                vc.nameDelegate = self
                present(vc, animated: true, completion: nil)
            }
        default:
            break
        }
    }

    

}

//MARK:TableViewData
@available(iOS 13.0, *)
extension PersonViewController: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return modules.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! PersonCell
        if userSelf != nil{
            modules.removeLast()
            modules.append("退出登录")
        }
        cell.moduleLabel.text = modules[indexPath.item]
        return cell
    }
    
    //MARK:DidSelect
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        currentIndex = indexPath
        if indexPath.row == 4{
            if userSelf != nil{
                let alert = UIAlertController(title: "退出登录？", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { [self] (default) in
                    if userSelf != nil{
                        userSelf = nil
                        LC.userLogout()
                        //更新视图
                        modules.removeLast()
                        modules.append("登录")
                        moduleTableView.reloadData()
                        userName.text = "username"
                        avatarBottomLabel.alpha = avatarBottomLabelAlpha
                        avatarBottomLabel.text = "点击登录"
                        userAvatar.image = UIImage(systemName: "person.fill")
                    }
                }))
                alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (cancel) in
                    UIView.animate(withDuration: 0.2) { [self] in
                        moduleTableView.cellForRow(at: currentIndex)?.isSelected = false
                    }
                }))
                present(alert, animated: true, completion: nil)
            }else{
                Login.showLogin1(namebackDelegate: self, turnToSignUpDelegate: self, viewcontroller: self)
            }
        }else if indexPath.row == 3{
            let alert = UIAlertController(title: "设置", message: nil, preferredStyle: .actionSheet)
            alert.addAction(UIAlertAction(title: setions[0], style: .default, handler: { (editInfo) in
                print("编辑资料")
            }))
            alert.addAction(UIAlertAction(title: setions[1], style: .default, handler: { (editPassword) in
                print("编辑密码")
            }))
            alert.addAction(UIAlertAction(title: setions[2], style: .destructive, handler: { (deleteUser) in
                print("注销账号")
            }))
            alert.addAction(UIAlertAction(title: setions[3], style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
        }else{
            switch indexPath.row {
            case 0:
                Module = .myCollect
                pushPersonDetailView(title: "我的收藏")
            case 1:
                Module = .myBorrow
                pushPersonDetailView(title: "我的借阅")
            case 2:
                Module = .myShare
                pushPersonDetailView(title: "我的分享")
            case 3:
                Module = .set
            case 4:
                Module = .loginout
            default:
                break
            }
        }
    }
    
    private func pushPersonDetailView(title:String){
        personDetailViewController.navigationItem.title = title
        personDetailViewController.cancelSelectedDelegate = self
        navigationController?.pushViewController(personDetailViewController, animated: true)
    }
    
}

//MARK:PickAvatarDelegate
@available(iOS 13.0, *)
extension PersonViewController: PickAvatarDelegate{
    func sendAvatar(name: String) {
        userAvatar.image = UIImage(named: name)
        clearView.removeFromSuperview()
    }
}
//MARK:TurnToSignUp
@available(iOS 13.0, *)
extension PersonViewController: LoginTurnSignUp{
    func turnSignUp() {
        Login.showSignUp(namebackDelegate: self, viewcontroller: self)
    }
}
//MARK:UserLogin
@available(iOS 13.0, *)
extension PersonViewController: nameBack{
    func getName(username: String) {
        //tableView dataSource更新
        modules.removeLast()
        modules.append("退出登录")
        self.moduleTableView.reloadData()
        //更新视图
        userName.text = username
        if let avatar = userSelf?.avatar{
            let image = UIImage(named: avatar)
            userAvatar.image = image
        }
        avatarBottomLabel.alpha = 0
    }
}
//MARK:CancelSelectedDelegate
@available(iOS 13.0, *)
extension PersonViewController: CancelSelectedDelegate{
    internal func cancelSelected() {
        UIView.animate(withDuration: 0.3) { [self] in
            moduleTableView.cellForRow(at: currentIndex)?.isSelected = false
        }
    }
}
